<template>
	<view class="chat-container">
		<!-- 聊天记录区域 -->
		<scroll-view 
			scroll-y 
			class="chat-list" 
			:scroll-top="scrollTop"
			:scroll-with-animation="true"
			@scrolltoupper="loadMoreMessages"
			:scroll-into-view="scrollToMessage"
			@scroll="onScroll"
			:id="scrollViewId"
		>
			<!-- 加载更多提示 -->
			<view v-if="hasMore" class="loading-more">加载更多消息...</view>
			
			<!-- 消息列表 -->
			<view 
				v-for="(message, index) in messages" 
				:key="index"
				:class="['message-item', message.type === 'user' ? 'message-right' : 'message-left']"
				:id="'msg-' + index"
			>
				<!-- 客服消息布局 -->
				<template v-if="message.type === 'service'">
					<view class="message-info">
						<view class="avatar-wrapper">
							<text class="user-name">{{serviceName}}</text>
							<image :src="serviceAvatar" class="avatar"></image>
						</view>
					</view>
					<view class="message-content">
						<view class="message-bubble">
							<text>{{message.content}}</text>
						</view>
						<text class="message-time">{{message.time}}</text>
					</view>
				</template>
				
				<!-- 用户消息布局 -->
				<template v-else>
					<view class="message-content">
						<view class="message-bubble">
							<text>{{message.content}}</text>
						</view>
						<text class="message-time">{{message.time}}</text>
					</view>
					<view class="message-info">
						<view class="avatar-wrapper">
							<text class="user-name">{{userName}}</text>
							<image :src="userAvatar" class="avatar"></image>
						</view>
					</view>
				</template>
			</view>
		</scroll-view>
		
		<!-- 输入区域 -->
		<view class="input-area">
			<view class="input-box">
				<input 
					type="text" 
					v-model="inputMessage" 
					placeholder="请输入您的问题" 
					@confirm="sendMessage"
					:disabled="!isConnected"
					:focus="inputFocus"
					@blur="handleInputBlur"
					@focus="handleInputFocus"
				/>
				<view class="input-tools">
					<text class="tool-icon" @tap="toggleQuickQuestions">💬</text>
				</view>
			</view>
			<button 
				class="send-btn" 
				:class="{'send-btn-disabled': !inputMessage.trim() || !isConnected}"
				@tap="sendMessage"
			>发送</button>
		</view>
		
		<!-- 快捷问题弹窗 -->
		<view class="quick-questions" v-if="showQuickQuestionsPanel">
			<view class="quick-questions-header">
				<text>常见问题</text>
				<text class="close-btn" @tap="toggleQuickQuestions">×</text>
			</view>
			<view class="quick-questions-list">
				<view 
					v-for="(question, index) in quickQuestions" 
					:key="index"
					class="quick-question-item"
					@tap="selectQuickQuestion(question)"
				>
					{{question}}
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				messages: [
					{
						type: 'service',
						content: '您好，我是您的专属客服小D，很高兴为您服务！请问有什么可以帮您？',
						time: '10:00'
					}
				],
				inputMessage: '',
				scrollTop: 0,
				scrollToMessage: '',
				hasMore: false,
				isConnected: true,
				showQuickQuestionsPanel: false,
				userAvatar: '/static/img/defaultAvatar.png',
				serviceAvatar: '/static/img/defaultAvatar.png',
				userName: '用户23',
				serviceName: '客服小D',
				quickQuestions: [
					'如何修改行程目的地？',
					'如何申请发票？',
					'如何取消订单？',
					'如何评价行程？',
					'如何联系司机？',
					'如何申请退款？'
				],
				inputFocus: true,
				scrollViewId: 'chatScrollView',
				isFirstLoad: true
			}
		},
		onLoad() {
			// 页面加载时获取消息
			this.getMessages();
		},
		onReady() {
			// 页面渲染完成后，确保滚动到底部
			this.scrollToBottom();
		},
		onShow() {
			// 页面显示时，如果是首次加载，滚动到底部
			if (this.isFirstLoad) {
				this.scrollToBottom();
				this.isFirstLoad = false;
			}
		},
		methods: {
			// 监听滚动事件
			onScroll(e) {
				// 可以在这里处理滚动事件
				console.log('scroll', e);
			},
			
			// 滚动到底部方法
			scrollToBottom() {
				// 使用nextTick确保DOM更新后再滚动
				this.$nextTick(() => {
					// 获取scroll-view的高度
					const query = uni.createSelectorQuery().in(this);
					query.select(`#${this.scrollViewId}`).boundingClientRect(data => {
						if (data) {
							// 设置一个足够大的scrollTop值
							this.scrollTop = 999999;
							
							// 同时设置scrollToMessage
							if (this.messages.length > 0) {
								const lastIndex = this.messages.length - 1;
								this.scrollToMessage = `msg-${lastIndex}`;
							}
						}
					}).exec();
				});
			},
			
			// 获取所有消息
			async getMessages() {
				try {
					const response = await uni.request({
						url: 'http://localhost:8080/ai/chatList',
						method: 'GET',
						data: {
							chatId: 2
						}
					});
					
					if (response.statusCode == 200) {
						// 将后端返回的消息数组映射到前端消息格式
						const historyMessages = response.data.map(item => ({
							type: item.messageType === 'USER' ? 'user' : 'service',
							content: item.text,
							time: this.formatTime(item.createTime)
						}));
						
						// 清空当前消息列表
						this.messages = [];
						
						// 如果有历史消息，添加分隔线
						if (historyMessages.length > 0) {
							this.messages = historyMessages;
							this.messages.push({
								type: 'service',
								content: '---以上是历史信息---',
								time: this.getCurrentTime()
							});
						}
						
						// 添加欢迎消息
						this.messages.push({
							type: 'service',
							content: '您好，我是您的专属客服小D，很高兴为您服务！请问有什么可以帮您？',
							time: this.getCurrentTime()
						});
						
						// 消息加载完成后滚动到底部
						setTimeout(() => {
							this.scrollToBottom();
						}, 300);
					}
				} catch (error) {
					console.log(error, "------error----");
					uni.showToast({
						title: '获取失败，请稍后再试',
						icon: 'none'
					});
					
					// 显示默认欢迎消息
					this.messages = [{
						type: 'service',
						content: '您好，我是您的专属客服小D，很高兴为您服务！请问有什么可以帮您？',
						time: this.getCurrentTime()
					}];
					
					// 错误情况下也需要滚动到底部
					setTimeout(() => {
						this.scrollToBottom();
					}, 300);
				}
			},
			
			// 格式化时间
			formatTime(timestamp) {
				if (!timestamp) return this.getCurrentTime();
				const date = new Date(timestamp);
				const hours = date.getHours().toString().padStart(2, '0');
				const minutes = date.getMinutes().toString().padStart(2, '0');
				return `${hours}:${minutes}`;
			},
			
			// 发送消息
			async sendMessage() {
				if (!this.inputMessage.trim() || !this.isConnected) return;
				
				let message = {
					type: 'user',
					content: this.inputMessage,
					chatId: 1,
					time: this.getCurrentTime()
				};

				// 先添加用户消息到列表
				this.messages.push(message);
				this.inputMessage = '';
				
				// 保持输入框焦点
				this.$nextTick(() => {
					this.inputFocus = true;
				});
				
				// 发送消息后滚动到底部
				this.scrollToBottom();
				
				// 发送消息到服务器
				try {
					const response = await uni.request({
						url: 'http://localhost:8080/ai/chat',
						method: 'GET',
						data: {
							prompt: message.content,
							chatId: 2
						}
					});
					
					if (response.statusCode == 200) {
						uni.showToast({
							title: '发送成功',
							icon: 'success'
						});
						
						const serviceMessage = {
							type: 'service',
							content: response.data,
							time: this.getCurrentTime()
						};
						
						// 添加服务端消息
						this.messages.push(serviceMessage);
						// 收到回复后滚动到底部
						this.scrollToBottom();
					} else {
						// 发送失败，移除用户消息
						this.messages.pop();
						uni.showToast({
							title: '发送失败，请稍后再试',
							icon: 'none'
						});
					}
				} catch (error) {
					// 发生错误，移除用户消息
					this.messages.pop();
					console.log(error, "------error----");
					uni.showToast({
						title: '发送失败，请稍后再试',
						icon: 'none'
					});
				}
			},
			
			// 显示/隐藏快捷问题
			toggleQuickQuestions() {
				this.showQuickQuestionsPanel = !this.showQuickQuestionsPanel;
			},
			
			// 处理输入框失去焦点
			handleInputBlur() {
				this.inputFocus = false;
			},
			
			// 处理输入框获得焦点
			handleInputFocus() {
				this.inputFocus = true;
			},
			
			// 选择快捷问题
			selectQuickQuestion(question) {
				this.inputMessage = question;
				this.showQuickQuestionsPanel = false;
				// 选择快捷问题后自动获取焦点
				this.$nextTick(() => {
					this.inputFocus = true;
				});
			},
			
			// 获取当前时间
			getCurrentTime() {
				const now = new Date();
				const hours = now.getHours().toString().padStart(2, '0');
				const minutes = now.getMinutes().toString().padStart(2, '0');
				return `${hours}:${minutes}`;
			},
			
			// 加载更多消息
			loadMoreMessages() {
				if (!this.hasMore) return;
				
				uni.showLoading({ title: '加载中...' });
				setTimeout(() => {
					// 这里添加加载历史消息的逻辑
					uni.hideLoading();
				}, 1000);
			}
		}
	}
</script>

<style>
.chat-container {
	display: flex;
	flex-direction: column;
	height: 100vh;
	background-color: #f5f5f5;
	position: relative;
}

.chat-list {
	flex: 1;
	padding: 20rpx;
	padding-bottom: 120rpx;
	display: flex;
	flex-direction: column;
	background-color: #f5f5f5;
	position: relative;
	z-index: 1;
	height: calc(100vh - 120rpx);
}

.message-item {
	display: flex;
	margin-bottom: 30rpx;
	animation: slideUp 0.3s ease-out;
	position: relative;
}

.message-left {
	justify-content: flex-start;
}

.message-right {
	justify-content: flex-end;
}

@keyframes slideUp {
	from {
		opacity: 0;
		transform: translateY(20rpx);
	}
	to {
		opacity: 1;
		transform: translateY(0);
	}
}

.message-info {
	display: flex;
	align-items: flex-start;
	margin: 0 20rpx;
	flex-shrink: 0;
}

.avatar-wrapper {
	display: flex;
	flex-direction: column;
	align-items: center;
	width: 80rpx;
}

.message-left .avatar-wrapper {
	align-items: flex-start;
}

.message-right .avatar-wrapper {
	align-items: flex-end;
}

.avatar {
	width: 80rpx;
	height: 80rpx;
	border-radius: 50%;
	margin-top: 10rpx;
}

.user-name {
	font-size: 24rpx;
	color: #666;
	margin-bottom: 4rpx;
	width: 100%;
	text-align: center;
	white-space: nowrap;
	overflow: hidden;
	text-overflow: ellipsis;
}

.message-left .user-name {
	text-align: left;
}

.message-right .user-name {
	text-align: right;
}

.message-content {
	max-width: 70%;
	margin-top: 40rpx;
}

.message-left .message-content {
	margin-left: 0;
}

.message-right .message-content {
	margin-right: 0;
}

.message-bubble {
	padding: 20rpx;
	border-radius: 12rpx;
	font-size: 28rpx;
	line-height: 1.5;
	word-break: break-all;
	box-shadow: 0 2rpx 4rpx rgba(0,0,0,0.1);
}

.message-left .message-bubble {
	background-color: #ffffff;
	color: #333;
	border-top-left-radius: 0;
}

.message-right .message-bubble {
	background-color: #007AFF;
	color: #ffffff;
	border-top-right-radius: 0;
}

.message-time {
	font-size: 24rpx;
	color: #999;
	margin-top: 10rpx;
	display: block;
}

.message-right .message-time {
	text-align: right;
}

.input-area {
	padding: 20rpx;
	background-color: #ffffff;
	border-top: 1rpx solid #eee;
	display: flex;
	align-items: center;
	position: fixed;
	bottom: 0;
	left: 0;
	right: 0;
	z-index: 2;
}

.input-box {
	flex: 1;
	display: flex;
	align-items: center;
	background-color: #f5f5f5;
	border-radius: 36rpx;
	padding: 0 20rpx;
	margin-right: 20rpx;
}

.input-box input {
	flex: 1;
	height: 72rpx;
	font-size: 28rpx;
}

.input-tools {
	display: flex;
	align-items: center;
}

.tool-icon {
	font-size: 40rpx;
	padding: 10rpx;
}

.send-btn {
	width: 120rpx;
	height: 72rpx;
	line-height: 72rpx;
	background-color: #007AFF;
	color: #ffffff;
	font-size: 28rpx;
	border-radius: 36rpx;
	padding: 0;
}

.send-btn-disabled {
	background-color: #cccccc;
}

.quick-questions {
	position: fixed;
	bottom: 120rpx;
	left: 0;
	right: 0;
	background-color: #ffffff;
	border-radius: 20rpx 20rpx 0 0;
	box-shadow: 0 -2rpx 10rpx rgba(0,0,0,0.1);
	z-index: 100;
}

.quick-questions-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 30rpx;
	border-bottom: 1rpx solid #eee;
}

.quick-questions-header text {
	font-size: 32rpx;
	color: #333;
}

.close-btn {
	font-size: 40rpx;
	color: #999;
	padding: 0 20rpx;
}

.quick-questions-list {
	padding: 20rpx;
	max-height: 600rpx;
	overflow-y: auto;
}

.quick-question-item {
	padding: 20rpx;
	background-color: #f5f5f5;
	border-radius: 8rpx;
	margin-bottom: 20rpx;
	font-size: 28rpx;
	color: #333;
}

.quick-question-item:active {
	opacity: 0.7;
}

.loading-more {
	text-align: center;
	font-size: 24rpx;
	color: #999;
	padding: 20rpx 0;
}
</style> 